/*  PrimeBlaster
    by Kjetil Eide 
    kjetile445@gmail.com

    This file is part of PrimeBlaster

    PrimeBlaster is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    PrimeBlaster is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PrimeBlaster.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.eide.spaceship;

import java.util.ArrayList;
import java.util.Random;

public class PrimeNumbers {
	/* the first 38 primes are implemented in this game */
	/* index 0-37 */
	private static final int[] PRIMES = new int[] {
		  2,   3,   5,   7,  11,  13,  17,  19,  23,  29,
		 31,  37,  41,  43,  47,  53,  59,  61,  67,  71,
		 73,  79,  83,  89,  97, 101, 103, 107, 109, 113,
		127, 131, 137, 139, 149, 151, 157, 163};
	
	/**
	 * Find two numbers that multiplied together gives
	 * the number n.
	 * does not neccecarily return prime factors.
	 * returns null if n is prime
	 * 
	 */
	
	public static int[] getFactors(int n) {
		ArrayList<Integer> factors = new ArrayList<Integer>();
		int index = 0;
		int[] returnFactors = new int[2];
		Random rnd = new Random();
		
		
		while (n != 1) {
			if (n % PRIMES[index] == 0) {
				n /= PRIMES[index];
				factors.add(PRIMES[index]);
			} else {
				index++;
				//System.out.println("idx: " + index);
			}
		}

		int numberOfFactors = factors.size();
		
		if (numberOfFactors < 2) {
			returnFactors = null;
		} else {
			while(numberOfFactors > 2) {
				int index1 = rnd.nextInt(numberOfFactors);
				int index2 = (index1 + 1) % numberOfFactors;
				factors.set(index1, factors.get(index1) * factors.get(index2));
				factors.remove(index2);
				numberOfFactors = factors.size();
			}
			for (int i = 0; i < 2; i++) {
				returnFactors[i] = factors.get(i);
			}
		}
		return returnFactors;
	}
	
	public static boolean isPrime(int n) {
		int i = 0;
		boolean isPrime = false;
		
		while(PRIMES[i] <= n) {
			if (n == PRIMES[i]) {
				isPrime = true;
			}
			i++;
		}
		return isPrime;
	}
}
